<template>
    <fieldset>
        <legend>二级联动</legend>
        省: 
        <select v-model="sel1" @change="provienceChange(sel1)">
            <option :value="item.id" v-for="item in provience" :key="item.id">{{item.name}}</option>
        </select>
        市:
        <select class="se" v-model="sel2" @change="citysChange(sel2)">
            <option v-for="item in citys" :key="item.id" :value="item.id">{{item.name}}</option>
        </select>
        县：
        <select  v-model="sel3">
            <option v-for="item in  county" :key="item.id" :value="item.id">{{item.name}}</option>
        </select>
    </fieldset>
</template>

<script>
let se = document.querySelector('.se')
import * as api from '@/api/select'
    export default {
        data(){
            return {
                provience:[],
                // 选择省的ID
                sel1:1,
                // 选择市的ID
                sel2:"",
                // 选择县的ID
                sel3:"",
                
                // 市
                citys:[],
                // 县
                county:[]
            }
        },
        mounted(){
            api.fetchData()
            .then(res=>{
                // console.log(res);
                let data = res.data.data.filter(item=>item.parentId == 0)
                this.provience = data
                
                // 获取默认第一条的id
                let pid  = data[0].id
                this.provienceChange(pid)
            })
          
        },
        methods:{
            provienceChange(pid){
                // 当选择的省发生变化的时候，获取选择的省对应的 id ,发起请求，请求市的数据
                api.fetchCity(pid)
                .then(res=>{
                    this.citys = res 
                    // 默认选中 市
                    this.sel2 = res[0].id
                        
                    

                    // 获取市第一条id
                    let cid = res[0].id
                    this.citysChange(cid)
                })
            },
            citysChange(cid){
                api.fetchCounty(cid)
                .then(res=>{
                    // console.log(res);
                    this.county = res
                   
                    if(this.county.length > 0){
                        this.sel3 = res[0].id
                    }
                   
                })
            }
        }
    }
</script>

<style scoped>
    select{
        width: 100px;
    }
</style>